import { Commit } from "vuex";
import { State, FetchAreasFormServe, Area, FetchPrintHtml, AreaMap } from "./interface";
import storage from "@/utils/Storage";
import * as model from "@/model";
export * from "./interface";
import { get } from "lodash";

export const AREAS_FETCH_SUCESS = "AREAS_FETCH_SUCESS"; // 区域加载成功

function saveAreasToLocal(areas: Area[], version: number) {
  storage.set(`areas`, areas);
  storage.set(`areas_version`, version);
}

function getAreasFromLocal() {
  return storage.get("areas") || [];
}

function getAreasVsFromLocal() {
  return storage.get("areas_version") || 0;
}

/**
 * 将 tree json 转为 set集合
 */
function getAreaSetList(areas: Area[]): AreaMap {
  return areas.reduce((acc, area: Area) => {
    const _acc = Object.assign(acc, {
      [area.pathid]: area
    });
    return Object.assign(_acc, get(area, "childrens.length", 0) ? getAreaSetList(area.childrens) : {});
  }, {});
}

function getAreasSetFromLocal() {
  return storage.get("areas_set") || {};
}

/**
 * 通用数据
 */

const state = () => ({
  areas: getAreasFromLocal(), // 区域
  areasVs: getAreasVsFromLocal(), // 区域版本
  areasSet: getAreasSetFromLocal() // 区域字典
});

const actions = {
  async fetchPrintHtml(context: { commit: Commit, state: State }, payload: FetchPrintHtml): Promise<string> {
    const _model: any = model;
    const data: any = await _model[payload.modal](payload.args);
    return data;
  }
};

const mutations = {
  [AREAS_FETCH_SUCESS](state: State, payload: FetchAreasFormServe) {
    if (payload.areas_list && payload.areas_list.length) {
      state.areas = payload.areas_list;
      state.areasVs = payload.api_version;
      state.areasSet = getAreaSetList(state.areas);
      storage.set("areas_set", state.areasSet);
      saveAreasToLocal(payload.areas_list, payload.api_version);
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
